// const autojsUtils = require('./modules/autojs-utils');
// vodafone ghs ui
"ui";

const Constant = require("./constant.js");

auto();

device.keepScreenOn();

// 之前保存的钱包
Constant.initMtnAndPin();
// 是否显示钱包
const showPinInput = Constant.isNeedPinInput();
console.log("showPinInput: " + showPinInput);

// 防止重复启动
let canStartScript = true;

// 点击展示pin入口次数
let resetPinClickTimes = 0;

ui.layout(
    <frame h="*" w="*" bg="#FFFFFF">
        <vertical>
            <text id="sceneName"
                w="*"
                h="auto"
                gravity="center"
                marginTop="16"
                textColor="red"
                textStyle="bold"
                textSize="16"
                text={Constant.WALLET_VODAFONE_GHS_NAME} />

            <input id="wallet"
                marginTop="16"
                hint="请输入钱包号码, 带0开头"
                text={Constant.getMtn()}
                textSize="14" />

            <input id="pin"
                marginTop="16"
                hint="请输入钱包PIN"
                text={Constant.getPin()}
                visibility={showPinInput}
                textSize="14" />

            <button id="saveAndStart"
                marginTop="16"
                text="启动脚本（不要重复点击）" />
        </vertical>

        <button id="resetPin"
            layout_gravity="right|bottom"
            w="auto" h="auto"
            marginBottom="40"
            marginRight="10"
            bg="#00000000"
            textColor="#00000000"
            textSize="8sp"
            text="重置pin" />
    </frame>
);


ui.resetPin.click(function () {
    resetPinClickTimes += 1;
    // console.log("resetPinClickTimes:" + resetPinClickTimes);

    if ((resetPinClickTimes > 0) && (resetPinClickTimes % 3 === 0)) {
        resetPinClickTimes = 0;
        ui.pin.setVisibility(android.view.View.VISIBLE);
    }
});

ui.saveAndStart.click(function () {
    // 防止重复启动
    if (!canStartScript) {
        console.log("canStartScript: " + canStartScript);
        return;
    }
    canStartScript = false;

    var name = ui.wallet.text();
    var pin = ui.pin.text();

    if (!name || (name.length <= 8)) {
        canStartScript = true;
        toast("钱包号错误!");
        return;
    }

    if (!pin || (pin.length !== 4)) {
        canStartScript = true;
        toast("pin错误!");
        return;
    }

    // 弹框确认
    confirm("务必确认PIN码 (第1次)", "号码:" + name + "\nPIN:" + pin).then(value => {
        //当点击确定后会执行这里, value为true或false, 表示点击"确定"或"取消"
        if (value) {
            confirm("务必确认PIN码 (第2次)", "号码:" + name + "\nPIN:" + pin).then(value => {
                //当点击确定后会执行这里, value为true或false, 表示点击"确定"或"取消"
                if (value) {
                    confirm("务必确认PIN码 (第3次)", "号码:" + name + "\nPIN:" + pin).then(value => {
                        //当点击确定后会执行这里, value为true或false, 表示点击"确定"或"取消"
                        if (value) {
                            confirm("务必确认PIN码 (第4次)", "号码:" + name + "\nPIN:" + pin).then(value => {
                                //当点击确定后会执行这里, value为true或false, 表示点击"确定"或"取消"
                                if (value) {
                                    confirm("务必确认PIN码 (第5次)", "号码:" + name + "\nPIN:" + pin).then(value => {
                                        //当点击确定后会执行这里, value为true或false, 表示点击"确定"或"取消"
                                        if (value) {
                                            // 保存本地
                                            Constant.setMtn(name);
                                            Constant.setPin(pin);

                                            // 隐藏pin
                                            ui.pin.setVisibility(android.view.View.GONE);

                                            // toast(name + "," + pin + " 已启动脚本");

                                            setTimeout(() => {
                                                // 启动脚本
                                                threads.start(function () {
                                                    canStartScript = true;
                                                    //在新线程执行的代码
                                                    main();
                                                });
                                            }, 1000);
                                        } else {
                                            canStartScript = true;
                                        }
                                    });
                                } else {
                                    canStartScript = true;
                                }
                            });
                        } else {
                            canStartScript = true;
                        }
                    });
                } else {
                    canStartScript = true;
                }
            });
        } else {
            canStartScript = true;
        }
    });
});



const BaseSmsUtil = require("./baseSmsUtil.js");
const BaseApiUrl = require("./baseApiUrl.js");
const BaseHttpUtil = require("./baseHttpUtil.js");

const VodafoneGhsAppOpen = require("./vodafoneGhsAppOpen.js");
const VodafoneGhsPageUtil = require("./vodafoneGhsPageUtil.js");
const VodafoneGhsFunAction = require("./vodafoneGhsFunAction.js");


// 测试转账
// let testMtnTransfer = true;

// 转账信息
let targetTransferAmount = "";
let targetTransferId = "";
let targetTransferAccount = "";
let targetTransferReference = "";

const initTransfer = (data) => {
    targetTransferAmount = data.amount + "";
    targetTransferId = data.id + "";
    targetTransferAccount = data.mtn + "";
    targetTransferReference = data.reference + "";
}

const isValidTransfer = () => {
    let result1 = targetTransferAmount || "";
    let result2 = targetTransferId || "";
    let result3 = targetTransferAccount || "";

    return ((result1.length > 0) && (result2.length > 0) && (result3.length > 0));
}

const cleanTransfer = () => {
    targetTransferAmount = "";
    targetTransferId = "";
    targetTransferAccount = "";
    targetTransferReference = "";
}

const printTransferLog = () => {
    console.log(Constant.UI_SDK_VERSION + "targetTransferAmount: " + targetTransferAmount + ",\ntargetTransferId: " + targetTransferId + ",\ntargetTransferAccount: " + targetTransferAccount + ",\ntargetTransferReference: " + targetTransferReference);
}

/** 启动脚本逻辑 */
function main() {
    // 设置坐标宽高
    // setScreenMetrics(720, 1640);
    console.log("w:" + device.width + " ,h:" + device.height);

    // 程序结束自动 隐藏控制台
    console.show(true);
    console.setMaxLines(15);


    // 转账信息
    targetTransferAmount = "";
    targetTransferId = "";
    targetTransferAccount = "";
    targetTransferReference = "";

    // 是否需要重启app
    let isNeedRestartWalletApp = false;

    // 是否需要重启脚本
    let isNeedRestartScript = false;

    // 上传短信
    BaseSmsUtil.syncSmsData(false, Constant.WALLET_VODAFONE_GHS_MNO);

    console.log(Constant.UI_SDK_VERSION + "当前设备: " + Constant.getMtn());
    // sleep(5 * 1000);

    // vodafone 钱包
    VodafoneGhsAppOpen.openVodafoneApp();

    // 上传短信 
    let lastSmsList = [];
    BaseSmsUtil.syncSmsData(false, Constant.WALLET_VODAFONE_GHS_MNO);
    sleep(2 * 1000);

    // 记录循环次数
    let loopTimes = 0;

    while (true) {
        // sleep(1000);

        // 次数+1
        loopTimes += 1;

        // 清空转账信息
        cleanTransfer();

        // 页面状态
        let pageStatus = VodafoneGhsPageUtil.doCheckPageStatus();
        let isLoginPage = pageStatus.isLoginPage;
        let isPinPage = pageStatus.isLoginPinPage;
        let isServicesPage = pageStatus.isServicesPage;
        let isHomePage = pageStatus.isHomePage;
        let isSendMoneyPage = pageStatus.isSendMoneyPage;
        let isSendMoneyAccountInputPage = pageStatus.isSendMoneyAccountInputPage;
        let isBillCheckConfirmPage = pageStatus.isBillCheckConfirmPage;
        let isBillListPage = pageStatus.isBillListPage;

        if (isBillCheckConfirmPage) {
            // 进入首页
            back();
            sleep(1000);

        } else if (isBillListPage) {
            // 进入首页
            back();
            sleep(1000);

        } else if (isSendMoneyPage) {
            // 进入首页
            back();
            sleep(1000);

        } else if (isSendMoneyAccountInputPage) {
            // 进入首页
            back();
            sleep(1000);
            back();
            sleep(1000);

        } else if (isSendMoneyAccountInputPage) {
            // 进入首页
            back();
            sleep(1000);
            back();
            sleep(1000);
            back();
            sleep(1000);
        }

        // 判断是否在 momo 应用内
        let isInMomoApp = true;
        //VodafoneGhsPageUtil.isInMomoApp();
        if (!isInMomoApp) {
            sleep(1 * 1000);
            home();
            sleep(2 * 1000);
            VodafoneGhsAppOpen.openVodafoneApp();

            // 上传短信
            BaseSmsUtil.syncSmsData(false, Constant.WALLET_VODAFONE_GHS_MNO);
            sleep(1 * 1000);

            // 清空控制台
            // console.clear();
            continue;
        }

        // 上传短信
        BaseSmsUtil.syncSmsData(false, Constant.WALLET_VODAFONE_GHS_MNO);
        sleep(1 * 1000);

        // 获取脚本状态信息
        let url = BaseApiUrl.checkOperStatus();
        let checkOperStatusParams = { phone: Constant.getMtn(), mno: Constant.WALLET_VODAFONE_GHS_MNO }
        let checkOperStatusResult = BaseHttpUtil.sendPostSync(url, checkOperStatusParams)
        if (checkOperStatusResult !== null) {
            isNeedRestartWalletApp = checkOperStatusResult.momo || false;
            isNeedRestartScript = checkOperStatusResult.script || false;
        } else {
            isNeedRestartWalletApp = false;
            isNeedRestartScript = false;
        }

        if (isNeedRestartScript) {
            sleep(1 * 1000);
            // 清空控制台
            console.clear();
            continue;
        }

        // 判断是否要重启app
        if (isNeedRestartWalletApp) {
            // 走关闭流程
            VodafoneGhsAppOpen.closeVodafoneApp();

            // 走重启流程
            VodafoneGhsAppOpen.openVodafoneApp();

            // 清空控制台
            console.clear();
            continue;

        } else {

            // 判断是否为登录-手机号页
            if (isLoginPage) {
                // 清空控制台
                console.clear();

                // 走登录-手机号流程
                let doLoginResult = VodafoneGhsFunAction.doLogin();
                if (doLoginResult) {
                    // 判断是否为 pin 页
                    isPinPage = VodafoneGhsPageUtil.doOpenLoginPinPage();
                }
            }

            // 判断是否为登录-PIN页
            if (isPinPage) {
                // 清空控制台
                console.clear();

                // 走登录-PIN流程
                let doPinResult = VodafoneGhsFunAction.doPin();
                if (doPinResult) {
                    // 判断是否为 服务页
                    isServicesPage = VodafoneGhsPageUtil.doOpenServicesPage();
                }
            }

            // 判断是否 服务页
            if (isServicesPage) {
                // 点击 cash
                let doClickHomeTabResult = VodafoneGhsFunAction.doClickHomeTab();
                if (doClickHomeTabResult) {
                    // 判断是否打开pin页
                    let doOpenLoginPinPageResult = VodafoneGhsPageUtil.doOpenLoginPinPage();
                    if (doOpenLoginPinPageResult) {
                        // 走登录-PIN流程
                        let doPinResult = VodafoneGhsFunAction.doPin();
                        if (doPinResult) {
                            // 判断是否为 首页
                            isHomePage = VodafoneGhsPageUtil.doOpenHomePage();
                        }
                    }
                }
            }

            // 判断是否为首页
            if (isHomePage) {
                // 清空控制台
                console.clear();

                // 上传余额
                console.log(Constant.UI_SDK_VERSION + "isHome-开始查余额");
                let currentBalance = VodafoneGhsFunAction.doGetHomeBalance();
                let detailInfo = {
                    mno: Constant.WALLET_VODAFONE_GHS_MNO,
                    phone: Constant.getMtn(),
                    currentBalance: currentBalance,
                    bills: []
                }
                let balanceUrl = BaseApiUrl.saveBills();
                BaseHttpUtil.sendPostSync(balanceUrl, detailInfo)

                // 获取转账信息
                cleanTransfer();

                // 查询转账信息
                let url = BaseApiUrl.getMtnTransferAccount();
                let checkTransferParams = { num: "1", phone: Constant.getMtn(), mno: Constant.WALLET_VODAFONE_GHS_MNO }
                let checkTransferParamsResult = BaseHttpUtil.sendPostSync(url, checkTransferParams)
                if (checkTransferParamsResult !== null) {
                    if (checkTransferParamsResult.length > 0) {
                        initTransfer(checkTransferParamsResult[0]);
                    } else {
                        cleanTransfer();
                    }
                } else {
                    cleanTransfer();
                }

                // 清空控制台
                console.clear();

                // 打印转账信息
                printTransferLog();

                // 判断是否需要转账
                if (isValidTransfer()) {
                    console.log(Constant.UI_SDK_VERSION + "==== 需要执行转账");
                    // 走打开 Send Money 流程
                    let doClickSendMoneyResult = VodafoneGhsFunAction.doClickSendMoney();
                    if (doClickSendMoneyResult) {
                        // 判断是否进入send money页
                        let doOpenSendMoneyPageResult = VodafoneGhsPageUtil.doOpenSendMoneyPage();
                        if (doOpenSendMoneyPageResult) {
                            // 打开 vodafone payment
                            let doClickVodafonePaymentResult = VodafoneGhsFunAction.doClickVodafonePayment();
                            if (doClickVodafonePaymentResult) {
                                // 判断是否为 Send Money input account 页
                                let doOpenInputTargetAccountPageResult = VodafoneGhsPageUtil.doOpenInputTargetAccountPage();
                                if (doOpenInputTargetAccountPageResult) {
                                    // 清空控制台
                                    console.clear();

                                    // 走 输入钱包号 流程
                                    let doInputTargetAccountPageResult = VodafoneGhsFunAction.doInputTargetAccount(targetTransferAccount, targetTransferAmount, targetTransferReference);
                                    if (doInputTargetAccountPageResult) {
                                        // 判断是否为失败页
                                        let doOpenSendMoneyPreCheckPageResult = VodafoneGhsPageUtil.doOpenSendMoneyPreCheckPage();
                                        if (doOpenSendMoneyPreCheckPageResult.isFail) {
                                            // 转账失败，返回首页
                                            back();
                                            sleep(1000);
                                        } else {
                                            // 判断是否为 转账确认 页
                                            // 点击确认转账按键
                                            let doConfirmSendMoneyPageResult = VodafoneGhsFunAction.doConfirmSendMoney();
                                            if (doConfirmSendMoneyPageResult) {
                                                // 判断是否为 输入密码页
                                                let doOpenSendMoneyPasswordPageResult = VodafoneGhsPageUtil.doOpenSendMoneyPasswordPage();
                                                if (doOpenSendMoneyPasswordPageResult) {
                                                    // 输入密码
                                                    let doOpenSendMoneyPasswordPageResult = VodafoneGhsFunAction.doInputSendMoneyPassword();
                                                    if (doOpenSendMoneyPasswordPageResult) {
                                                        let doOpenSendMoneyResultPageResult = VodafoneGhsPageUtil.doOpenSendMoneyResultPage();
                                                        // 判断是否为转账成功页
                                                        if (doOpenSendMoneyResultPageResult.isSuccess) {
                                                            // 保存转账成功
                                                            let url = BaseApiUrl.saveMtnTransferResult();
                                                            let transferResultSuccessParams = { id: targetTransferId, response: "", status: "2", txnId: "", mno: Constant.WALLET_VODAFONE_GHS_MNO }
                                                            BaseHttpUtil.sendPostSync(url, transferResultSuccessParams)
                                                            sleep(1 * 1000);

                                                            // 点击返回
                                                            let doClickTransferDoneAndGoBackResult = VodafoneGhsFunAction.doClickTransferDoneAndGoBack();
                                                            if (doClickTransferDoneAndGoBackResult) {
                                                                console.log(Constant.UI_SDK_VERSION + "确认转账成功, 返回Send Money页");
                                                            }
                                                        }
                                                        // 判断是否为转账失败页
                                                        if (doOpenSendMoneyResultPageResult.isFail) {
                                                            // 保存转账成功
                                                            let url = BaseApiUrl.saveMtnTransferResult();
                                                            let transferResultFailParams = { id: targetTransferId, response: "", status: "3", txnId: "", mno: Constant.WALLET_VODAFONE_GHS_MNO }
                                                            BaseHttpUtil.sendPostSync(url, transferResultFailParams)
                                                            sleep(1 * 1000);

                                                            // 点击返回
                                                            let doClickTransferFailAndGoBackResult = VodafoneGhsFunAction.doClickTransferFailAndGoBack();
                                                            if (doClickTransferFailAndGoBackResult) {
                                                                console.log(Constant.UI_SDK_VERSION + "转账失败, 返回Send Money页");
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // 判断是否为 首页
            isHomePage = VodafoneGhsPageUtil.doOpenHomePage();

            // 判断是否为首页
            if (isHomePage) {
                // 清空控制台
                // console.clear();

                sleep(3 * 1000);
                // 清空控制台
                console.clear();
                // 上传短信
                BaseSmsUtil.syncSmsData(false, Constant.WALLET_VODAFONE_GHS_MNO);

                // let doClickSendMoneyResult = VodafoneGhsFunAction.doClickSendMoney();
                // if (doClickSendMoneyResult) {
                //     // 判断是否进入send money页
                //     let doOpenSendMoneyPageResult = VodafoneGhsPageUtil.doOpenSendMoneyPage();
                //     if (doOpenSendMoneyPageResult) {
                //         // 点击左上角返回，不能直接back()
                //         click(58, 146)
                //     }
                // }

                // 如果循环了
                if ((loopTimes % 100) === 0) {
                    back();
                }

                sleep(5 * 1000);
                continue;

                if (false) {
                    let canCheckBillList = false;
                    if ((!lastSmsList) || (lastSmsList.length === 0)) {
                        canCheckBillList = true;
                    } else {
                        // 上传短信
                        let curSmsList = BaseSmsUtil.fetchSmsData(null, Constant.WALLET_VODAFONE_GHS_MNO);
                        console.log(Constant.UI_SDK_VERSION + "curSmsList条数: " + curSmsList.length);
                        console.log(Constant.UI_SDK_VERSION + "lastSmsList条数: " + lastSmsList.length);

                        for (checkBillIndex = 0; checkBillIndex < 3; checkBillIndex++) {
                            // 如果有新的短信，就去查流水
                            let isPaymentSmsChanged = BaseSmsUtil.isSmsListChangedForGhsVodafone(curSmsList, lastSmsList);

                            if (isPaymentSmsChanged) {
                                canCheckBillList = true;
                                lastSmsList = curSmsList;
                                console.log(Constant.UI_SDK_VERSION + "短信发生变动，需要重新查询流水")
                                break;
                            }

                            // 3秒后重新来查短信
                            curSmsList.length = 0;
                            curSmsList = null;
                            sleep(3000);
                            curSmsList = BaseSmsUtil.fetchSmsData(null, Constant.WALLET_VODAFONE_GHS_MNO);
                        }
                    }

                    if (canCheckBillList) {
                        let doClickTransacitonsResult = VodafoneGhsFunAction.doClickCheckBills();
                        if (doClickTransacitonsResult) {
                            // 清空控制台
                            // console.clear();

                            // 判断是否为 bill check confirm 页
                            let isBillCheckConfirmPageResult = VodafoneGhsPageUtil.doOpenBillCheckConfirmPage();
                            if (isBillCheckConfirmPageResult) {
                                // 操作打开流水页
                                let doClickBillCheckProceedResult = VodafoneGhsFunAction.doClickBillCheckProceed();
                                // 判断是否打开流水页
                                if (doClickBillCheckProceedResult) {
                                    // 输入pin码
                                    let doBillCheckPinInputResult = VodafoneGhsFunAction.doInputBillCheckPin();
                                    if (doBillCheckPinInputResult) {
                                        // 判断是否进入流水页
                                        let doOpenBillListPageResult = VodafoneGhsPageUtil.doOpenBillListPage();
                                        if (doOpenBillListPageResult) {
                                            // 读取流水页
                                            let doScanBillsForEachScreenResult = VodafoneGhsFunAction.doScanBillsForEachScreen();
                                            if (doScanBillsForEachScreenResult) {
                                                sleep(5 * 1000);
                                                // 清空控制台
                                                // console.clear();
                                                // 上传短信
                                                BaseSmsUtil.syncSmsData(false, Constant.WALLET_VODAFONE_GHS_MNO);
                                                continue;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            sleep(1 * 1000);

            // 最后都不能匹配成功，
            // 走关闭流程
            VodafoneGhsAppOpen.closeVodafoneApp();

            // 走重启流程
            VodafoneGhsAppOpen.openVodafoneApp();

            // 清空控制台
            console.clear();
        }
    }
}



